package com.homestead.controller;


import com.homestead.constant.Constant;
import com.homestead.exception.BusinessException;
import com.homestead.resp.CommonResponse;
import com.homestead.utils.CommonResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Oauth2 控制器
 * @author 1
 */
@RestController
@RequestMapping("/oauth")
@Api(tags = {"Oauth2服务接口"})
@Slf4j
public class OAuthController {
    @Resource
    private TokenEndpoint tokenEndpoint;

    @PostMapping("/token")
    @ApiOperation(value = "获取token入口")
    public CommonResponse<Map<String, Object>> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) {
        try {
            return custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());
        } catch (BusinessException be) {
            log.error("获取token入口 error, message={}", be.getMessage(), be);
            return CommonResponseUtil.fail(be.getCode(), be.getMessage());
        } catch (HttpRequestMethodNotSupportedException e) {
            return CommonResponseUtil.fail(Constant.ERROR_CODE, e.getMessage());
        }
    }

    /**
     * 自定义 Token 返回对象
     *
     * @param accessToken
     * @return
     */
    private CommonResponse<Map<String, Object>> custom(OAuth2AccessToken accessToken) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
        Map<String, Object> data = new LinkedHashMap<>(token.getAdditionalInformation());
        data.put("accessToken", token.getValue());
        data.put("expireIn", token.getExpiresIn());
        data.put("scopes", token.getScope());
        if (token.getRefreshToken() != null) {
            data.put("refreshToken", token.getRefreshToken().getValue());
        }
        return CommonResponseUtil.successObj(data);
    }

}